﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using YAPL.Language.Ast;
using YAPL.Util;

namespace YAPL.Language.SourceParser.XML.NodeParsers {
	public class XmlFunctionDefParser : XmlExpressionParser {
		public XmlFunctionDefParser(XmlInputParser inputParser) : base(inputParser) {}
		public override Expression ParseNode(XElement node) {
			var nameAttribute = node.Attribute(XmlNames.FunctionNameAttribute);
			Require.NotNull(nameAttribute);
			Require.NotEmpty(nameAttribute.Value);

			var paramsNode = node.Element(XmlNames.ParametersExpression);
			var bodyNode = node.Element(XmlNames.CodeBlockExpression);

			Require.NotNull(bodyNode);
			var parameters = new List<ParameterExpression>();

			if (paramsNode!= null)
				paramsNode.Elements().Each(paramNode => parameters.Add((ParameterExpression) Parser.ParseNode(paramNode)));

			var body = (CodeBlockExpression) Parser.ParseNode(bodyNode);

			return Expressions.Function(nameAttribute.Value, parameters, body);
		}
	}
}
